package com.example.calculator1;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    public static final String TAG = "tag";
    private boolean isBind = false;

    ServiceConnection mServiceConn;
    CalcService mCalcService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn_start = findViewById(R.id.startService);
        Button btn_stop = findViewById(R.id.endService);
        Button btn_useService = findViewById(R.id.useServ);
        btn_start.setOnClickListener(view -> {
            Log.v(TAG, "启动服务成功");
            Toast.makeText(MainActivity.this, "启动服务成功", Toast.LENGTH_SHORT).show();
            onButtonStartServiceClick(view);
        });
        btn_stop.setOnClickListener(view -> {
            Log.v(TAG, "关闭服务");
            onButtonStopServiceClick(view);
        });
        btn_useService.setOnClickListener(view -> {
            Log.v(TAG, "使用加法服务");
            AddClick(view);
        });
    }

    /**
     * 启动服务
     * */
    public void onButtonStartServiceClick(View view){
        Intent intent = new Intent(MainActivity.this, CalcService.class);
        mServiceConn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.v(TAG, "onServiceConnected");
                mCalcService = ((CalcService.LocalBinder) iBinder).getService();
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.v(TAG, "onServiceDisconnected");
            }
        };
        isBind = bindService(intent, mServiceConn, Service.BIND_AUTO_CREATE);
    }
    /**
     * 终止服务
     * */
    public void onButtonStopServiceClick(View view){
        if(isBind){
            unbindService(mServiceConn);
            Log.v(TAG, "关闭服务成功");
            Toast.makeText(MainActivity.this, "关闭服务成功", Toast.LENGTH_SHORT).show();
            isBind = false;
        } else {
            Toast.makeText(MainActivity.this, "关闭服务失败，没有连接到服务", Toast.LENGTH_SHORT).show();
            Log.v(TAG, "关闭服务失败，没有连接到服务");
        }
    }

    public void AddClick(View view){
        if(isBind){
            Toast.makeText(MainActivity.this, "Using service ADD:\n"
            + mCalcService.add(10, 5), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(MainActivity.this, "没有连接到服务", Toast.LENGTH_SHORT).show();
            Log.v(TAG, "使用服务失败，没有连接到服务");
        }
    }
}